<template>
  <view class="set-account-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 支付宝账户设置 -->
    <view class="form-container" v-if="type === 'alipay'">
      <view class="form-item">
        <text class="label">姓名</text>
        <input type="text" v-model="formData.name" placeholder="请输入姓名" placeholder-class="input-placeholder" />
      </view>
      
      <view class="form-item">
        <text class="label">账号</text>
        <input type="text" v-model="formData.account" placeholder="请填写支付宝账号" placeholder-class="input-placeholder" />
      </view>
      
      <view class="tips-container">
        <view class="tip-item">1. 为避免打款失败，请填写本人支付宝账号；</view>
        <view class="tip-item">2. 支付宝账号为手机号或邮箱，请勿填写银行卡号或微信号。</view>
      </view>
    </view>
    
    <!-- 银行卡账户设置 -->
    <view class="form-container" v-if="type === 'bank'">
      <view class="form-item">
        <text class="label">账户姓名</text>
        <input type="text" v-model="formData.name" placeholder="请输入姓名" placeholder-class="input-placeholder" />
      </view>
      
      <view class="form-item">
        <text class="label">开户银行</text>
        <view class="picker-container" @tap="showBankPicker">
          <text :class="['picker-text', {'placeholder': !formData.bankName}]">{{formData.bankName || '请选择开户银行'}}</text>
          <text class="iconfont icon-right"></text>
        </view>
      </view>
      
      <view class="form-item">
        <text class="label">开户省市</text>
        <view class="picker-container" @tap="showCityPicker">
          <text :class="['picker-text', {'placeholder': !formData.city}]">{{formData.city || '请选择开户省市'}}</text>
          <text class="iconfont icon-right"></text>
        </view>
      </view>
      
      <view class="form-item">
        <text class="label">银行卡号</text>
        <view class="card-input">
          <input type="number" v-model="formData.cardNumber" placeholder="请输入银行卡号" placeholder-class="input-placeholder" />
          <text class="scan-icon iconfont icon-scan" @tap="scanBankCard"></text>
        </view>
      </view>
      
      <!-- 添加银行卡识别按钮 -->
      <view class="form-item">
        <text class="label">银行卡识别</text>
        <view class="card-recognition">
          <button class="recognition-btn" @tap="showBankCardRecognition">识别银行卡</button>
        </view>
      </view>
    </view>
    
    <!-- 保存按钮 - 修复样式和位置 -->
    <view class="button-wrapper">
      <button class="save-button" :class="{'disabled': !isFormValid}" @tap="handleSave">保存</button>
    </view>
    
    <!-- 银行选择弹出层 -->
    <view class="bank-picker-popup" v-if="showBankPickerPopup">
      <view class="popup-mask" @tap="hideBankPicker"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择开户银行</text>
          <text class="popup-close" @tap="hideBankPicker">×</text>
        </view>
        
        <view class="search-box">
          <view class="search-input">
            <text class="search-icon iconfont icon-search"></text>
            <input 
              type="text" 
              v-model="bankSearchKeyword" 
              placeholder="请输入银行名称" 
              placeholder-class="search-placeholder"
              @input="searchBanks"
            />
          </view>
        </view>
        
        <scroll-view class="bank-list" scroll-y>
          <view 
            class="bank-item" 
            v-for="(bank, index) in filteredBankList" 
            :key="index"
            @tap="selectBank(bank)"
          >
            <text class="bank-name">{{ bank.name }}</text>
          </view>
        </scroll-view>
      </view>
    </view>
    
    <!-- 省市选择弹出层 -->
    <view class="city-picker-popup" v-if="showCityPickerPopup">
      <view class="popup-mask" @tap="hideCityPicker"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择开户省市</text>
          <text class="popup-close" @tap="hideCityPicker">×</text>
        </view>
        
        <view class="city-container">
          <!-- 左侧省份列表 -->
          <scroll-view class="province-list" scroll-y>
            <view 
              class="province-item" 
              v-for="(province, index) in provinceList" 
              :key="index"
              :class="{'active': selectedProvinceIndex === index}"
              @tap="selectProvince(index)"
            >
              <text class="province-name">{{ province.name }}</text>
            </view>
          </scroll-view>
          
          <!-- 右侧城市列表 -->
          <scroll-view class="city-list" scroll-y>
            <view 
              class="city-item" 
              v-for="(city, index) in currentCities" 
              :key="index"
              @tap="selectCity(city)"
            >
              <text class="city-name">{{ city.name }}</text>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
    
    <!-- 银行卡识别页面 -->
    <view class="bank-card-recognition-popup" v-if="showBankCardRecognitionPopup">
      <view class="popup-mask" @tap="hideBankCardRecognition"></view>
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">银行卡识别</text>
          <text class="popup-close" @tap="hideBankCardRecognition">×</text>
        </view>
        
        <view class="recognition-container">
          <!-- 预览区域 -->
          <view class="preview-area" v-if="bankCardImage">
            <image :src="bankCardImage" mode="aspectFit" class="preview-image"></image>
          </view>
          
          <!-- 上传按钮 -->
          <view class="upload-area" v-else>
            <view class="upload-btn" @tap="chooseBankCardImage">
              <text class="iconfont icon-camera"></text>
              <text class="upload-text">点击上传</text>
            </view>
            <text class="upload-tips">请确保银行卡清晰可见，避免反光和模糊</text>
          </view>
          
          <!-- 识别结果 -->
          <view class="recognition-result" v-if="recognitionResult">
            <view class="result-item">
              <text class="result-label">银行卡号：</text>
              <text class="result-value">{{ recognitionResult.number || '未识别' }}</text>
            </view>
            <view class="result-item">
              <text class="result-label">持卡人：</text>
              <text class="result-value">{{ recognitionResult.cardHolder || '未识别' }}</text>
            </view>
            <view class="result-item">
              <text class="result-label">银行名称：</text>
              <text class="result-value">{{ recognitionResult.bankName || '未识别' }}</text>
            </view>
            <view class="result-item">
              <text class="result-label">有效期：</text>
              <text class="result-value">{{ recognitionResult.validDate || '未识别' }}</text>
            </view>
          </view>
          
          <!-- 操作按钮 -->
          <view class="action-buttons">
            <button class="action-btn cancel-btn" @tap="hideBankCardRecognition">取消</button>
            <button class="action-btn confirm-btn" @tap="applyRecognitionResult" :disabled="!recognitionResult">应用识别结果</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import TechNavBar from '@/components/tech-nav-bar.vue'
import NavBar from '@/components/nav-bar/nav-bar.vue'
// 引入jweixin
import jweixin from 'jweixin-module'
import lrz from 'lrz';
import imageCutter from 'image-cutter';
// 引入省市区数据
import provincesData from '@/components/provinces.json'
import citiesData from '@/components/cities.json'
import areasData from '@/components/areas.json'
export default {
  components: {
    TechNavBar,
    NavBar
  },
  
  data() {
    return {
      type: 'alipay', // 默认支付宝类型
      formData: {
        name: '',
        account: '',
        bankName: '',
        bankCode: '',
        city: '',
        province: '', // 添加省份字段
        cityCode: '', // 添加城市代码字段
        cardNumber: ''
      },
      bankList: [], // 银行列表数据
      showBankPickerPopup: false, // 控制银行选择器弹出层显示
      bankSearchKeyword: '', // 银行搜索关键词
      filteredBankList: [], // 过滤后的银行列表
      
      // 省市选择器相关数据
      showCityPickerPopup: false, // 控制省市选择器弹出层显示
      provinceList: [], // 省份列表
      selectedProvinceIndex: 0, // 当前选中的省份索引
      selectedProvince: null, // 当前选中的省份
      selectedCity: null, // 当前选中的城市
      currentCities: [], // 当前省份下的城市列表
      accountInfo: null, // 保存完整的账户信息
      
      // 银行卡识别相关数据
      showBankCardRecognitionPopup: false, // 控制银行卡识别弹出层显示
      bankCardImage: '', // 银行卡图片
      recognitionResult: null, // 识别结果
      isRecognizing: false, // 是否正在识别中
      
      // JSSDK相关
      isJssdkInitialized: false, // 是否已初始化JSSDK
      isIOS: false
    }
  },
  
  computed: {
    isFormValid() {
      // 姓名校验：2-20 位中文或带"·"
      const isNameValid = this.validateName(this.formData.name);

      if (this.type === 'alipay') {
        return isNameValid && !!this.formData.account;
      }

      // 银行卡校验：16-19 位且通过 Luhn 算法
      const isCardValid = this.validateCardNumber(this.formData.cardNumber);

      return (
        isNameValid &&
        isCardValid &&
        !!this.formData.bankName &&
        !!this.formData.city
      );
    }
  },
  
  onLoad(options) {
    // iOS 首次进入自动刷新
    // this.isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
    // if (this.isIOS && !sessionStorage.getItem('iosRefreshed_setAccount')) {
    //   sessionStorage.setItem('iosRefreshed_setAccount', 'true');
    //   window.location.reload();
    //   return;
    // }
    if (options.type) {
      this.type = options.type
    }
    this.loadAccountInfo()
    this.loadBankList()
    this.loadProvinceAndCityData() // 加载省市数据
    
    // 初始化JSSDK
    this.initJssdkConfig()
  },
  onShow() {
		},
  methods: {
    // 初始化JSSDK配置
    initJssdkConfig() {
      // 获取当前页面URL（去除hash部分）
      const url = window.location.href.split('#')[0];
      
      // 请求后端获取签名配置
      uni.request({
        url: `${uni.$config.baseUrl}/wx/jssdk/config`,
        method: 'GET',
        data: { url: url },
        header: {
          'Authorization': uni.getStorageSync('token')
        },
        success: (res) => {
          if (res.data && res.data.code === 200) {
            const config = res.data.data;
            this.configJweixin(config);
          } else {
            uni.showToast({
              title: '微信配置失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('获取JSSDK配置失败:', err);
          uni.showToast({
            title: '微信配置失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 配置jweixin
    configJweixin(config) {
      jweixin.config({
        debug: false, // 开启调试模式
        appId: config.appId, // 必填，公众号的唯一标识
        timestamp: config.timestamp, // 必填，生成签名的时间戳
        nonceStr: config.nonceStr, // 必填，生成签名的随机串
        signature: config.signature, // 必填，签名
        jsApiList: [
          'chooseImage', // 从本地相册选择图片或使用相机拍照
          'uploadImage', // 上传图片
          'scanQRCode', // 扫一扫
          'getLocation', // 获取地理位置
          'openLocation' // 使用微信内置地图查看位置
        ] // 必填，需要使用的JS接口列表
      });
      
      // 配置成功回调
      jweixin.ready(() => {
        console.log('jweixin配置成功');
        this.isJssdkInitialized = true;
      });
      
      // 配置失败回调
      jweixin.error((err) => {
        console.error('jweixin配置失败:', err);
        uni.showToast({
          title: '微信配置失败',
          icon: 'none'
        });
      });
    },
    
    // 加载账户信息
    async loadAccountInfo() {
      uni.showLoading({
        title: '加载中...'
      });
      
      try {
        // 从本地存储获取技师ID
        const userInfo = uni.getStorageSync('userInfo');
        const techId = userInfo ? userInfo.techId : null;
        
        if (!techId) {
          uni.showToast({
            title: '未获取到技师信息，请重新登录',
            icon: 'none'
          });
          return;
        }
        
        // 构建请求参数
        const params = {
          technicianId: techId,
          accountType: this.type === 'alipay' ? 1 : 2 // 1-支付宝，2-银行卡
        };
        
        // 调用后端API获取账户列表
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/tehcAccount/tehcAccount/listAll`,
          method: 'GET',
          data: params,
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (result.data.code === 200) {
          // 获取账户列表
          const accountList = result.data.rows || [];
          
          // 查找当前类型的账户
          if (accountList.length > 0) {
            const currentAccount = accountList.find(account => 
              account.accountType === (this.type === 'alipay' ? 1 : 2)
            );
            
            if (currentAccount) {
              // 保存完整的账户信息，包括ID
              this.accountInfo = currentAccount;
              
              // 支付宝账户
              if (this.type === 'alipay' && currentAccount.account) {
                this.formData.name = currentAccount.name || '';
                this.formData.account = currentAccount.account || '';
              } 
              // 银行卡账户
              else if (this.type === 'bank') {
                this.formData.name = currentAccount.name || '';
                this.formData.bankName = currentAccount.bankName || '';
                this.formData.city = currentAccount.city || '';
                this.formData.cardNumber = currentAccount.cardNumber || '';
                this.formData.bankCode = currentAccount.bankCode || '';
                this.formData.province = currentAccount.province || '';
                this.formData.cityCode = currentAccount.cityCode || '';
              }
            }
          }
        } else {
          console.error('获取账户信息失败:', result.data.msg);
        }
      } catch (err) {
        console.error('获取账户信息失败:', err);
        uni.showToast({
          title: '获取账户信息失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 加载银行列表
    async loadBankList() {
      try {
        // 这里可以调用后端API获取银行列表
        // 暂时使用静态数据
        this.bankList = [
          { code: 'ICBC', name: '工商银行' },
          { code: 'CCB', name: '建设银行' },
          { code: 'ABC', name: '农业银行' },
          { code: 'PSBC', name: '邮政储蓄银行' },
          { code: 'BOC', name: '中国银行' },
          { code: 'COMM', name: '交通银行' },
          { code: 'CMB', name: '招商银行' },
          { code: 'SPDB', name: '浦发银行' },
          { code: 'CIB', name: '兴业银行' },
          { code: 'CITIC', name: '中信银行' },
          { code: 'CEB', name: '光大银行' },
          { code: 'CMBC', name: '民生银行' },
          { code: 'GDB', name: '广发银行' },
          { code: 'PAB', name: '平安银行' },
          { code: 'HXB', name: '华夏银行' },
          { code: 'CGB', name: '广州银行' }
        ];
        this.filteredBankList = [...this.bankList];
      } catch (error) {
        console.error('加载银行列表失败:', error);
      }
    },
    
    // 显示银行选择器
    showBankPicker() {
      this.showBankPickerPopup = true;
      this.bankSearchKeyword = '';
      this.filteredBankList = [...this.bankList];
    },
    
    // 隐藏银行选择器
    hideBankPicker() {
      this.showBankPickerPopup = false;
    },
    
    // 搜索银行
    searchBanks() {
      if (!this.bankSearchKeyword) {
        this.filteredBankList = [...this.bankList];
        return;
      }
      
      this.filteredBankList = this.bankList.filter(bank => 
        bank.name.includes(this.bankSearchKeyword)
      );
    },
    
    // 选择银行
    selectBank(bank) {
      this.formData.bankName = bank.name;
      this.formData.bankCode = bank.code;
      this.hideBankPicker();
    },
    
    // 加载省市数据
    async loadProvinceAndCityData() {
      try {
        // 使用本地JSON文件数据
        this.provinceList = provincesData;
        
        // 初始化当前城市列表为第一个省份的城市
        if (this.provinceList.length > 0) {
          const firstProvinceCode = this.provinceList[0].code;
          this.currentCities = citiesData.filter(city => city.provinceCode === firstProvinceCode);
        }
      } catch (error) {
        console.error('加载省市数据失败:', error);
        // 如果加载失败，使用空数组
        this.provinceList = [];
        this.currentCities = [];
      }
    },
    
    // 显示省市选择器
    showCityPicker() {
      this.showCityPickerPopup = true;
    },
    
    // 隐藏省市选择器
    hideCityPicker() {
      this.showCityPickerPopup = false;
    },
    
    // 选择省份
    selectProvince(index) {
      this.selectedProvinceIndex = index;
      this.selectedProvince = this.provinceList[index];
      // 根据省份code筛选对应的城市
      this.currentCities = citiesData.filter(city => city.provinceCode === this.selectedProvince.code);
      this.selectedCity = null; // 重置选中的城市
    },
    
    // 选择城市
    selectCity(city) {
      this.selectedCity = city;
      
      // 直接设置表单数据并关闭弹窗
      if (this.selectedProvince && city) {
        this.formData.province = this.selectedProvince.name;
        this.formData.city = `${this.selectedProvince.name} ${city.name}`;
        this.formData.cityCode = city.code;
        this.hideCityPicker();
      }
    },
    
    // 扫描银行卡
    scanBankCard() {
      // 检查JSSDK是否已初始化
      if (!this.isJssdkInitialized) {
      uni.showToast({
          title: '微信配置未完成，请稍后再试',
        icon: 'none'
        });
        return;
      }
      
      // 使用jweixin的扫一扫功能
      jweixin.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果
        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
        success: (res) => {
          console.log('扫码结果:', res);
          // 尝试从扫码结果中提取银行卡号
          const cardNumber = this.extractCardNumber(res.resultStr);
          if (cardNumber) {
            this.formData.cardNumber = cardNumber;
          } else {
            uni.showToast({
              title: '未能识别银行卡号',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('扫码失败:', err);
          uni.showToast({
            title: '扫码失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 从扫码结果中提取银行卡号
    extractCardNumber(result) {
      // 银行卡号通常是16-19位数字
      const cardNumberRegex = /\d{16,19}/;
      const match = result.match(cardNumberRegex);
      return match ? match[0] : null;
    },
    
    // 显示银行卡识别页面
    showBankCardRecognition() {
      this.showBankCardRecognitionPopup = true;
      this.bankCardImage = '';
      this.recognitionResult = null;
    },
    
    // 隐藏银行卡识别页面
    hideBankCardRecognition() {
      this.showBankCardRecognitionPopup = false;
    },
    
    // 选择银行卡图片
    chooseBankCardImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original','compressed'], // 只使用压缩模式
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 设置图片预览
          this.bankCardImage = tempFilePath;
          
          // 显示识别中状态
          this.isRecognizing = true;
          uni.showLoading({
            title: '处理图片中...',
            mask: true
          });

          // 压缩图片
          this.compressAndUploadImage(tempFilePath);
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },

    // 压缩并上传图片
    compressAndUploadImage(tempFilePath) {
      console.log('压缩前的图片路径：', tempFilePath);
      // 先获取图片信息
      uni.getImageInfo({
        src: tempFilePath,
        success: (imageInfo) => {
          // 计算压缩比例，目标大小不超过1MB
          const maxSize = 1024 * 1024; // 1MB
          const quality = Math.min(maxSize / imageInfo.size, 1);
          
          // 压缩图片
          lrz(tempFilePath, { quality: 0.3 }) // 设置压缩质量，0-1 范围
              .then((res) => {
                console.log('压缩后的图片路径：', res.file); // 压缩后的图片 Blob 对象
                  const compressedImagePath = URL.createObjectURL(res.file); // 转换为图片路径
              
                  console.log('压缩后的图片路径：', compressedImagePath);
                  // 上传压缩后的图片
              this.uploadImageForOcr(compressedImagePath);
             }).catch((error) => {
            console.error('压缩失败：', error);
          });
        },
        fail: (err) => {
          console.error('获取图片信息失败:', err);
          // 如果获取信息失败，尝试直接上传原图
          this.uploadImageForOcr(tempFilePath);
        }
      });
    },

    // 上传图片进行OCR识别
    uploadImageForOcr(filePath) {
      uni.uploadFile({
        url: `${uni.$config.baseUrl}/common/ocr/bankCard/upload`,
        filePath: filePath,
        name: 'file',
        success: (uploadRes) => {
          let result;
          try {
            result = JSON.parse(uploadRes.data);
          } catch (e) {
            console.error('解析响应失败:', e);
            uni.showToast({
              title: '识别失败，服务器响应无效',
              icon: 'none'
            });
            return;
          }
          
          // 处理文件大小超限的情况
          if (result.errcode === 45002) {
            uni.showToast({
              title: '图片太大，请重新选择较小的图片',
              icon: 'none',
              duration: 2000
            });
            return;
          }
          
          if (result && result.code === 200) {
            // 识别成功，更新表单数据
            this.recognitionResult = result.data;
            console.log('银行卡识别结果:', this.recognitionResult);
            
            // 保存图片URL（如果后端返回）
            if (this.recognitionResult.imageUrl) {
              this.bankCardImage = this.recognitionResult.imageUrl;
            }
            
            // 自动填充表单
            if (this.recognitionResult.number) {
              this.formData.cardNumber = this.recognitionResult.number;
            }
            
            if (this.recognitionResult.cardHolder) {
              this.formData.name = this.recognitionResult.cardHolder;
            }
            
            if (this.recognitionResult.bankName) {
              // 查找匹配的银行
              const matchedBank = this.bankList.find(bank => 
                bank.name.includes(this.recognitionResult.bankName) || 
                this.recognitionResult.bankName.includes(bank.name)
              );
              
              if (matchedBank) {
                this.formData.bankName = matchedBank.name;
                this.formData.bankCode = matchedBank.code;
              }
            }
            
            // 显示成功提示
            uni.showToast({
              title: '识别成功',
              icon: 'success'
            });
          } else {
            // 处理特定错误情况
            if (result.msg && result.msg.includes('请选择要上传的图片')) {
              uni.showToast({
                title: '请选择要上传的图片',
                icon: 'none'
              });
            } else {
              uni.showToast({
                title: result.msg || '识别失败',
                icon: 'none'
              });
            }
          }
        },
        fail: (err) => {
          console.error('上传文件失败:', err);
          
          // 检查网络错误
          if (err.errMsg && err.errMsg.includes('timeout')) {
            uni.showToast({
              title: '网络超时，请重试',
              icon: 'none'
            });
          } else {
            uni.showToast({
              title: '上传文件失败:' + JSON.stringify(err),
              icon: 'none'
            });
          }
        },
        complete: () => {
          // 隐藏loading和重置识别状态
          this.isRecognizing = false;
          uni.hideLoading();
        }
      });
    },
    
    // 应用识别结果
    applyRecognitionResult() {
      if (!this.recognitionResult) return;
      
      // 自动填充表单
      if (this.recognitionResult.number) {
        this.formData.cardNumber = this.recognitionResult.number;
      }
      
      if (this.recognitionResult.cardHolder) {
        this.formData.name = this.recognitionResult.cardHolder;
      }
      
      if (this.recognitionResult.bankName) {
        // 查找匹配的银行
        const matchedBank = this.bankList.find(bank => 
          bank.name.includes(this.recognitionResult.bankName) || 
          this.recognitionResult.bankName.includes(bank.name)
        );
        
        if (matchedBank) {
          this.formData.bankName = matchedBank.name;
          this.formData.bankCode = matchedBank.code;
        }
      }
      
      // 关闭识别页面
      this.hideBankCardRecognition();
      
      // 提示用户
      uni.showToast({
        title: '已应用识别结果',
        icon: 'success'
      });
    },
    
    // 保存账户信息
    async handleSave() {
      // 额外的显式校验，给出友好提示
      if (!this.validateName(this.formData.name)) {
        uni.showToast({ title: '姓名格式不正确', icon: 'none' });
        return;
      }

      if (this.type === 'bank' && !this.validateCardNumber(this.formData.cardNumber)) {
        uni.showToast({ title: '请输入有效的银行卡号', icon: 'none' });
        return;
      }

      if (!this.isFormValid) {
        // 兜底校验（按钮可能被强制启用）
        uni.showToast({ title: '请完善信息', icon: 'none' });
        return;
      }
      
      // 从本地存储获取技师ID
      const userInfo = uni.getStorageSync('userInfo');
      const techId = userInfo ? userInfo.techId : null;
      if (!techId) {
        uni.showToast({
          title: '未获取到技师信息，请重新登录',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({
        title: '保存中...'
      });
      
      try {
        // 构建提交的账户数据
        let accountData = {
          technicianId: techId,
          accountType: this.type === 'alipay' ? 1 : 2, // 1-支付宝，2-银行卡
          name: this.formData.name,
          isDefault: 1 // 设为默认账户
        };
        
        // 如果已有账户信息，则是修改操作，需要带上ID
        if (this.accountInfo && this.accountInfo.id) {
          accountData.id = this.accountInfo.id;
        }
        
        // 根据账户类型添加不同的字段
        if (this.type === 'alipay') {
          accountData.account = this.formData.account;
        } else {
          accountData.bankName = this.formData.bankName;
          accountData.bankCode = this.formData.bankCode;
          accountData.city = this.formData.city;
          accountData.province = this.formData.province;
          accountData.cityCode = this.formData.cityCode;
          accountData.cardNumber = this.formData.cardNumber;
        }
        
        // 确定请求方法：有ID则为修改，无ID则为新增
        const method = accountData.id ? 'PUT' : 'POST';
        const url = accountData.id 
          ? `${uni.$config.baseUrl}/tehcAccount/tehcAccount` 
          : `${uni.$config.baseUrl}/tehcAccount/tehcAccount`;
        
        // 调用后端API添加或修改账户
        const result = await uni.request({
          url: url,
          method: method,
          data: accountData,
          header: {
            'Content-Type': 'application/json',
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (result.data.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error(result.data.msg || '保存失败');
        }
      } catch (err) {
        console.error('保存账户信息失败:', err);
        uni.showToast({
          title: err.message || '保存失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    /*
     * 校验银行卡号是否有效（Luhn 算法）
     */
    validateCardNumber(number) {
      const card = String(number).replace(/\s+/g, '');
      if (!/^\d{16,19}$/.test(card)) return false;

      let sum = 0;
      for (let i = 0; i < card.length; i++) {
        let digit = parseInt(card[card.length - 1 - i], 10);
        if (i % 2 === 1) {
          digit *= 2;
          if (digit > 9) digit -= 9;
        }
        sum += digit;
      }
      return sum % 10 === 0;
    },

    /*
     * 校验姓名：仅限中文（可含"·"），长度 2-20
     */
    validateName(name) {
      return /^[\u4e00-\u9fa5·]{2,20}$/.test(name);
    },
  }
}
</script>

<style lang="scss" scoped>
.set-account-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx; /* 为底部按钮留出空间 */
  position: relative; /* 确保容器可以作为定位参考 */
  
  .form-container {
    background: #FFFFFF;
    margin: 20rpx;
    border-radius: 12rpx;
    
    .form-item {
      display: flex;
      align-items: center;
      min-height: 100rpx;
      border-bottom: 2rpx solid #F5F5F5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        width: 160rpx;
        font-size: 32rpx;
        color: #333333;
      }
      
      input {
        flex: 1;
        height: 100rpx;
        font-size: 32rpx;
      }
      
      .picker-container {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 100rpx;
        
        .picker-text {
          font-size: 32rpx;
          color: #333333;
          
          &.placeholder {
            color: #999999;
          }
        }
        
        .icon-right {
          font-size: 32rpx;
          color: #CCCCCC;
        }
      }
      
      .card-input {
        flex: 1;
        display: flex;
        align-items: center;
        
        input {
          flex: 1;
        }
        
        .scan-icon {
          padding: 0 20rpx;
          font-size: 40rpx;
          color: #2B85E4;
        }
      }
      
      .card-recognition {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        
        .recognition-btn {
          background-color: #2B85E4;
          color: #FFFFFF;
          font-size: 28rpx;
          padding: 10rpx 30rpx;
          border-radius: 30rpx;
          border: none;
          
          &::after {
            border: none;
          }
        }
      }
    }
  }
  
  .tips-container {
    padding: 30rpx;
    
    .tip-item {
      font-size: 28rpx;
      color: #FF0000;
      line-height: 1.5;
    }
  }
  
  /* 新增按钮包装器样式 */
  .button-wrapper {
    padding: 30rpx;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #FFFFFF;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100; /* 确保按钮在最上层 */
  }
  
  /* 修改按钮样式 */
  .save-button {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    background: #2B85E4;
    color: #FFFFFF;
    font-size: 32rpx;
    border-radius: 44rpx;
    border: none;
    
    &.disabled {
      opacity: 0.6;
    }
    
    &::after {
      border: none; /* 移除按钮默认边框 */
    }
  }
  
  // 银行选择器弹出层样式
  .bank-picker-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    
    .popup-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
    }
    
    .popup-content {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #FFFFFF;
      border-top-left-radius: 20rpx;
      border-top-right-radius: 20rpx;
      max-height: 70vh;
      display: flex;
      flex-direction: column;
      
      .popup-header {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100rpx;
        position: relative;
        border-bottom: 1rpx solid #EEEEEE;
        
        .popup-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333333;
        }
        
        .popup-close {
          position: absolute;
          right: 30rpx;
          font-size: 48rpx;
          color: #999999;
          line-height: 1;
        }
      }
      
      .search-box {
        padding: 20rpx 30rpx;
        
        .search-input {
          display: flex;
          align-items: center;
          height: 80rpx;
          background-color: #F5F5F5;
          border-radius: 40rpx;
          padding: 0 30rpx;
          
          .search-icon {
            font-size: 32rpx;
            color: #999999;
            margin-right: 10rpx;
          }
          
          input {
            flex: 1;
            height: 80rpx;
            font-size: 28rpx;
          }
        }
      }
      
      .bank-list {
        flex: 1;
        max-height: calc(70vh - 200rpx);
        
        .bank-item {
          padding: 30rpx;
          border-bottom: 1rpx solid #EEEEEE;
          
          .bank-name {
            font-size: 32rpx;
            color: #333333;
          }
          
          &:active {
            background-color: #F5F5F5;
          }
        }
      }
    }
  }
  
  // 省市选择器弹出层样式
  .city-picker-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    
    .popup-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
    }
    
    .popup-content {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #FFFFFF;
      border-top-left-radius: 20rpx;
      border-top-right-radius: 20rpx;
      max-height: 80vh;
      display: flex;
      flex-direction: column;
      
      .popup-header {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100rpx;
        position: relative;
        border-bottom: 1rpx solid #EEEEEE;
        
        .popup-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333333;
        }
        
        .popup-close {
          position: absolute;
          right: 30rpx;
          font-size: 48rpx;
          color: #999999;
          line-height: 1;
        }
      }
      
      .city-container {
        display: flex;
        height: 600rpx;
        
        .province-list {
          width: 240rpx;
          height: 100%;
          background-color: #F5F5F5;
          
          .province-item {
            padding: 30rpx 20rpx;
            border-bottom: 1rpx solid #EEEEEE;
            
            &.active {
              background-color: #FFFFFF;
              color: #2B85E4;
              position: relative;
              
              &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 6rpx;
                height: 36rpx;
                background-color: #2B85E4;
              }
            }
            
            .province-name {
              font-size: 28rpx;
              color: #333333;
            }
          }
        }
        
        .city-list {
          flex: 1;
          height: 100%;
          
          .city-item {
            padding: 30rpx 40rpx;
            border-bottom: 1rpx solid #EEEEEE;
            
            .city-name {
              font-size: 28rpx;
              color: #333333;
            }
            
            &:active {
              background-color: #F5F5F5;
            }
          }
        }
      }
    }
  }
  
  // 银行卡识别弹出层样式
  .bank-card-recognition-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    
    .popup-mask {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
    }
    
    .popup-content {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #FFFFFF;
      border-top-left-radius: 20rpx;
      border-top-right-radius: 20rpx;
      max-height: 90vh;
      display: flex;
      flex-direction: column;
      
      .popup-header {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100rpx;
        position: relative;
        border-bottom: 1rpx solid #EEEEEE;
        
        .popup-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333333;
        }
        
        .popup-close {
          position: absolute;
          right: 30rpx;
          font-size: 48rpx;
          color: #999999;
          line-height: 1;
        }
      }
      
      .recognition-container {
        flex: 1;
        padding: 30rpx;
        display: flex;
        flex-direction: column;
        
        .preview-area {
          width: 100%;
          height: 400rpx;
          background-color: #F5F5F5;
          border-radius: 12rpx;
          overflow: hidden;
          margin-bottom: 30rpx;
          
          .preview-image {
            width: 100%;
            height: 100%;
          }
        }
        
        .upload-area {
          width: 100%;
          height: 400rpx;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          background-color: #F5F5F5;
          border-radius: 12rpx;
          margin-bottom: 30rpx;
          
          .upload-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 200rpx;
            height: 200rpx;
            background-color: #FFFFFF;
            border-radius: 50%;
            box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
            
            .icon-camera {
              font-size: 80rpx;
              color: #2B85E4;
              margin-bottom: 10rpx;
            }
            
            .upload-text {
              font-size: 24rpx;
              color: #666666;
            }
          }
          
          .upload-tips {
            font-size: 24rpx;
            color: #999999;
            margin-top: 30rpx;
          }
        }
        
        .recognition-result {
          background-color: #F8F8F8;
          border-radius: 12rpx;
          padding: 20rpx;
          margin-bottom: 30rpx;
          
          .result-item {
            display: flex;
            margin-bottom: 20rpx;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .result-label {
              width: 160rpx;
              font-size: 28rpx;
              color: #666666;
            }
            
            .result-value {
              flex: 1;
              font-size: 28rpx;
              color: #333333;
            }
          }
        }
        
        .action-buttons {
          display: flex;
          justify-content: space-between;
          margin-top: auto;
          
          .action-btn {
            width: 48%;
            height: 88rpx;
            line-height: 88rpx;
            text-align: center;
            border-radius: 44rpx;
            font-size: 32rpx;
            
            &.cancel-btn {
              background-color: #F5F5F5;
              color: #666666;
            }
            
            &.confirm-btn {
              background-color: #2B85E4;
              color: #FFFFFF;
              
              &[disabled] {
                opacity: 0.6;
              }
            }
            
            &::after {
              border: none;
            }
          }
        }
      }
    }
  }
}

.input-placeholder {
  color: #999999;
}

.search-placeholder {
  color: #999999;
}
</style> 